package com.gzhryc.shared_device.oem.code.profit.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.gzhryc.common.NumberTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.base.enums.ELogState;
import com.gzhryc.shared_device.base.enums.EPayType;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.common.payment.dao.db.AlipayConfig;
import com.gzhryc.shared_device.common.payment.dao.db.AlipayOrder;
import com.gzhryc.shared_device.common.payment.dao.db.WXPayConfig;
import com.gzhryc.shared_device.common.payment.dao.db.WXPayOrder;
import com.gzhryc.shared_device.common.payment.dao.enums.ProjectWalletEnum;
import com.gzhryc.shared_device.common.payment.services.AlipayConfigService;
import com.gzhryc.shared_device.common.payment.services.AlipayOrderService;
import com.gzhryc.shared_device.common.payment.services.WXPayConfigService;
import com.gzhryc.shared_device.common.payment.services.WXPayOrderService;
import com.gzhryc.shared_device.oem.code.ConfigUtils;
import com.gzhryc.shared_device.oem.code.agent.dao.db.Agent;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentBusinessConfig;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentReferrerBusinessConfig;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationBusinessConfig;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationWallet;
import com.gzhryc.shared_device.oem.code.agent.services.AgentBusinessConfigService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentReferrerBusinessConfigService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationBusinessConfigService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationWalletService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentService;
import com.gzhryc.shared_device.oem.code.config.BusinessConfig;
import com.gzhryc.shared_device.oem.code.member.dao.db.Member;
import com.gzhryc.shared_device.oem.code.member.dao.enums.MemberEnum;
import com.gzhryc.shared_device.oem.code.member.services.MemberService;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceProfitUser;
import com.gzhryc.shared_device.oem.code.place.dao.models.IncomeRatioContent;
import com.gzhryc.shared_device.oem.code.place.services.PlaceProfitUserService;
import com.gzhryc.shared_device.oem.code.profit.UserProfitConstants;
import com.gzhryc.shared_device.oem.code.profit.dao.BusinessOrderUserProfitDao;
import com.gzhryc.shared_device.oem.code.profit.dao.db.AgentReferrerOrderProfit;
import com.gzhryc.shared_device.oem.code.profit.dao.db.BusinessOrder;
import com.gzhryc.shared_device.oem.code.profit.dao.db.BusinessOrderUserProfit;
import com.gzhryc.shared_device.oem.code.profit.dao.enums.BusinessOrderUserProfitEnum;
import com.gzhryc.shared_device.oem.code.profit.service.dto.BusinessOrderUserProfitSearch;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.dao.db.UserWallet;
import com.gzhryc.shared_device.oem.code.user.services.UserService;
import com.gzhryc.shared_device.oem.code.user.services.UserWalletService;

public class BusinessOrderUserProfitService {

    static Logger log = Logger.getLogger(BusinessOrderUserProfitService.class);

    public static BusinessOrderUserProfitService self(Date date) {
        return MultiDBTools.getService(BusinessOrderUserProfitService.class, date);
    }

    public static BusinessOrderUserProfitService self(String jdbcKey,Date date) {
        return MultiDBTools.getService(jdbcKey, BusinessOrderUserProfitService.class, date);
    }

    BusinessOrderUserProfitDao dao;

    public BusinessOrderUserProfitService(String jdbcKey,Date date) {
        this.dao = new BusinessOrderUserProfitDao(jdbcKey,date);
    }
    
    public List<BusinessOrderUserProfit> findBySearch(BusinessOrderUserProfitSearch search,Integer pageNo,Integer pageLimit){
        Conditions conditions = dao.buildConditions(search);
        conditions.and().ge("createDate", search.getStartCreateDate());
        conditions.and().lt("createDate", search.getEndCreateDate());
        try {
            return dao.findByCondition(conditions,pageNo,pageLimit);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public List<BusinessOrderUserProfit> findByTradeNo(String tradeNo){
        if(StringTools.isNotBlank(tradeNo)){
            Conditions conditions = new Conditions(BusinessOrderUserProfit.class);
            conditions.and().is("tradeNo",tradeNo);
            conditions.desc("userId");
            try {
                return dao.findByCondition(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public List<BusinessOrderUserProfit> findDivideByTradeNo(String tradeNo){
        if(StringTools.isNotBlank(tradeNo)){
            Conditions conditions = new Conditions(BusinessOrderUserProfit.class);
            conditions.and().is("tradeNo",tradeNo);
            conditions.and().is("state",BusinessOrderUserProfitEnum.State.Finish.index());
            conditions.desc("userId");
            try {
                return dao.findByCondition(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public Long countByTradeNo(String tradeNo){
        if(StringTools.isNotBlank(tradeNo)){
            Conditions conditions = new Conditions(BusinessOrderUserProfit.class);
            conditions.and().is("tradeNo",tradeNo);
            conditions.desc("userId");
            try {
                return dao.count(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return 0L;
    }

    public Long sumMoneyByUserIdAndState(Long userId,Integer state){
        if(userId != null && state != null){
            Conditions conditions = new Conditions(BusinessOrderUserProfit.class);
            conditions.and().is("userId",userId);
            conditions.and().is("state",state);

            try {
                return dao.sumMoneyByCondition(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return 0L;
    }

    public boolean dividedIncome(BusinessOrder businessOrder,OperateInfo operateInfo) throws LogicException {
        List<BusinessOrderUserProfit> temp = this.findDivideByTradeNo(businessOrder.getTradeNo());
        if(temp != null && temp.size() > 0){
            throw new LogicException("订单已分成");
        }
        
        if(StringTools.isBlank(operateInfo.getOperateNote())) {
        	operateInfo.setOperateNote("订单分成");
        }

        BusinessOrderUserProfit platformUser = null;
        Long accountGroupId = null;
        BusinessConfig config = ConfigUtils.getBusinessConfig();
        Agent agent = null;
        
        try {
	        //获取支付账号组
	        if(EPayType.EWallet.index().equals(businessOrder.getPayType())){
	            Member member = MemberService.self().getById(businessOrder.getMemberId());
	            if(member != null && StringTools.isNotBlank(member.getAppId())){
	            	if(MemberEnum.Type.AliUser.index().equals(member.getType())) {
	            		AlipayConfig alipayConfig = AlipayConfigService.self().getByAppId(member.getAppId());
		                if (alipayConfig.getAccountGroupId() != null) {
		                    accountGroupId = alipayConfig.getAccountGroupId();
		                }else{
		                    throw new LogicException("支付宝支付配置未设置账号组ID");
		                }
	            	}else {
	            		WXPayConfig wxPayConfig = WXPayConfigService.self().getByAppId(member.getAppId());
		                if (wxPayConfig.getAccountGroupId() != null) {
		                    accountGroupId = wxPayConfig.getAccountGroupId();
		                }else{
		                    throw new LogicException("微信支付配置未设置账号组ID");
		                }
	            	}
	            }else{
	                throw new LogicException("会员钱包支付，未找到会员信息或登陆应用ID");
	            }
	        }else if(EPayType.Alipay.index().equals(businessOrder.getPayType())){
	        	AlipayOrder alipayOrder = AlipayOrderService.self(businessOrder.getCreateDate()).getByTradeNo(businessOrder.getTradeNo());
	        	AlipayConfig alipayConfig = AlipayConfigService.self().getByAppId(alipayOrder.getAppId());
	            if (alipayConfig.getAccountGroupId() != null) {
	                accountGroupId = alipayConfig.getAccountGroupId();
	            }else{
	                throw new LogicException("支付宝支付配置未设置账号组ID");
	            }
	        }else {
	            WXPayOrder wxPayOrder = WXPayOrderService.self(businessOrder.getCreateDate()).getByTradeNo(businessOrder.getTradeNo());
	            WXPayConfig wxPayConfig = WXPayConfigService.self().getByAppId(wxPayOrder.getAppId());
	            if (wxPayConfig.getAccountGroupId() != null) {
	                accountGroupId = wxPayConfig.getAccountGroupId();
	            }else{
	                throw new LogicException("微信支付配置未设置账号组ID");
	            }
	        }
        }catch(LogicException e) {
        	//记录操作日志
            BusinessOrderLogService.self(businessOrder.getCreateDate()).add(businessOrder, operateInfo, ELogState.Fail.index(), e.getMessage());
        	throw e;
        }

        if(BusinessOrderService.self(businessOrder.getCreateDate()).incomeDivideLock(businessOrder.getTradeNo(),businessOrder.getIncomeMoney())) {
            boolean isSuccess = false;
            String divideError = null;
            try {
            	 agent = AgentService.self().getJoinByUserId(businessOrder.getPlaceUserId());
                 if(agent == null){
                     throw new LogicException("未找到网点代理信息");
                 }
                 
                List<BusinessOrderUserProfit> userProfitList = new ArrayList<>();
              
                Long incomeMoney = businessOrder.getIncomeMoney();

                platformUser = new BusinessOrderUserProfit();
                platformUser.setTradeNo(businessOrder.getTradeNo());
                platformUser.setOrderDate(businessOrder.getCreateDate());
                platformUser.setDeviceFunCode(businessOrder.getDeviceFunCode());
                platformUser.setBusinessType(businessOrder.getBusinessType());
                platformUser.setUserId(UserProfitConstants.PlatformServerUserId);
                platformUser.setAccountGroupId(accountGroupId);
                platformUser.setName(UserProfitConstants.PlatformServerUserName);
                platformUser.setRoleType(ERoleType.Sys.index());
                platformUser.setIncomeRatio(config.getServiceChargeRatio());
                platformUser.setMoney(0L);
                platformUser.setAgentId(agent.getUserId());       //代理ID
                platformUser.setPlaceId(businessOrder.getPlaceId());
                platformUser.setPlaceName(businessOrder.getPlaceName());
                platformUser.setProvince(businessOrder.getProvince());
                platformUser.setCity(businessOrder.getCity());
                platformUser.setCityArea(businessOrder.getCityArea());
                platformUser.setAreaCode(businessOrder.getAreaCode());
                platformUser.setState(BusinessOrderUserProfitEnum.State.Finish.index());
                platformUser.setCreateDate(new Date());
                userProfitList.add(platformUser);
                
                AgentBusinessConfig agentBusiCofnig = AgentBusinessConfigService.self().getByKeys(agent.getUserId(), businessOrder.getBusinessType());
                
                if(agentBusiCofnig != null && agentBusiCofnig.getServiceChargeRatio() >= 0) {	//支持0%分成
                	platformUser.setIncomeRatio(agentBusiCofnig.getServiceChargeRatio());
                	if(agentBusiCofnig.getServiceChargeRatio() > 0) {
	                	//计算成本
	                    Long money = NumberTools.proportion(incomeMoney, agentBusiCofnig.getServiceChargeRatio());
	                    platformUser.setMoney(money);
	
	                    incomeMoney = incomeMoney - money;
                	}
                }else if(config.getServiceChargeRatio() != null && config.getServiceChargeRatio() > 0) {
                    //计算成本
                    Long money = NumberTools.proportion(incomeMoney, config.getServiceChargeRatio());
                    platformUser.setMoney(money);

                    incomeMoney = incomeMoney - money;
                }

                //网点代理
                BusinessOrderUserProfit placeUser = new BusinessOrderUserProfit();
                placeUser.setTradeNo(businessOrder.getTradeNo());
                placeUser.setOrderDate(businessOrder.getCreateDate());
                placeUser.setDeviceFunCode(businessOrder.getDeviceFunCode());
                placeUser.setBusinessType(businessOrder.getBusinessType());
                placeUser.setUserId(agent.getUserId());
                placeUser.setAccountGroupId(accountGroupId);
                placeUser.setName(agent.getUser().getName());
                placeUser.setRoleType(ERoleType.Agent.index());
                placeUser.setIncomeRatio(0D);
                placeUser.setMoney(0L);
                placeUser.setAgentId(agent.getUserId());       //代理ID
                placeUser.setPlaceId(businessOrder.getPlaceId());
                placeUser.setPlaceName(businessOrder.getPlaceName());
                placeUser.setProvince(businessOrder.getProvince());
                placeUser.setCity(businessOrder.getCity());
                placeUser.setCityArea(businessOrder.getCityArea());
                placeUser.setAreaCode(businessOrder.getAreaCode());
                placeUser.setState(BusinessOrderUserProfitEnum.State.Finish.index());
                placeUser.setCreateDate(new Date());
                userProfitList.add(placeUser);
                
                //一个网点合伙人只有一个
                PlaceProfitUser partnerProfitUser = null;

                Long profitMoney = 0L;
                Double incomeRatio = 100D;
                List<PlaceProfitUser> placeProfitUserList = PlaceProfitUserService.self().findByPlaceId(businessOrder.getPlaceId());
                if(placeProfitUserList != null && placeProfitUserList.size() > 0){
                    for(PlaceProfitUser placeProfitUser : placeProfitUserList){
                    	if(ERoleType.Partner.index().equals(placeProfitUser.getRoleType())) {
                    		partnerProfitUser = placeProfitUser;
                    	}else {
	                        if(StringTools.isNotBlank(placeProfitUser.getIncomeRatioContent())){
	                            IncomeRatioContent incomeRatioContent = JsonTools.fromJson(placeProfitUser.getIncomeRatioContent(), IncomeRatioContent.class);
	                            for(IncomeRatioContent.Item item : incomeRatioContent.getItems()){
	                                if(item.getBusinessType().equals(businessOrder.getBusinessType())){
	                                    if(item.getIncomeRatio() != null && item.getIncomeRatio() > 0){
	                                        User user = UserService.self().getById(placeProfitUser.getUserId());
	
	                                        Long money = NumberTools.proportion(incomeMoney, item.getIncomeRatio());
	                                        profitMoney = profitMoney + money;
	                                        incomeRatio = incomeRatio - item.getIncomeRatio();
	
	                                        BusinessOrderUserProfit userProfit = new BusinessOrderUserProfit();
	                                        userProfit.setTradeNo(businessOrder.getTradeNo());
	                                        userProfit.setOrderDate(businessOrder.getCreateDate());
	                                        userProfit.setDeviceFunCode(businessOrder.getDeviceFunCode());
	                                        userProfit.setBusinessType(businessOrder.getBusinessType());
	                                        userProfit.setUserId(user.getId());
	                                        userProfit.setAgentId(agent.getUserId());       //代理ID
	                                        userProfit.setAccountGroupId(accountGroupId);
	                                        userProfit.setName(user.getName());
	                                        userProfit.setPhone(user.getPhone());
	                                        userProfit.setRoleType(placeProfitUser.getRoleType());
	                                        userProfit.setIncomeRatio(item.getIncomeRatio());
	                                        userProfit.setMoney(money);
	                                        userProfit.setPlaceId(businessOrder.getPlaceId());
	                                        userProfit.setPlaceName(businessOrder.getPlaceName());
	                                        userProfit.setProvince(businessOrder.getProvince());
	                                        userProfit.setCity(businessOrder.getCity());
	                                        userProfit.setCityArea(businessOrder.getCityArea());
	                                        userProfit.setAreaCode(businessOrder.getAreaCode());
	                                        userProfit.setNote(placeProfitUser.getNote());
	                                        userProfit.setState(BusinessOrderUserProfitEnum.State.Finish.index());
	                                        userProfit.setCreateDate(new Date());
	                                        userProfitList.add(userProfit);
	                                    }
	                                }
	                            }
	                        }
                    	}
                    }
                }
                
                if(partnerProfitUser != null) {
                	Long money = 0L;
                	Double staffIncomeRatio = 0D;
                	
                    if(incomeRatio > 0) {
	            		//如果有合伙人，则优先给合伙人分
                    	boolean flag = true;		//用于判断合伙人分成比例进行了单独设置
	            		if(StringTools.isNotBlank(partnerProfitUser.getIncomeRatioContent())){
	                        IncomeRatioContent incomeRatioContent = JsonTools.fromJson(partnerProfitUser.getIncomeRatioContent(), IncomeRatioContent.class);
	                        for(IncomeRatioContent.Item item : incomeRatioContent.getItems()){
	                            if(item.getBusinessType().equals(businessOrder.getBusinessType())){
	                            	flag = false;		//进行了单独配置
	                            	if(item.getIncomeRatio() != null && item.getIncomeRatio() > 0){
	                            		 if(incomeRatio >= item.getIncomeRatio()) {
	                            			 staffIncomeRatio = item.getIncomeRatio();
	                            			 money = NumberTools.proportion(incomeMoney, staffIncomeRatio);
	                            			 incomeRatio = incomeRatio - staffIncomeRatio;
	                            		 }else {
	                            			 staffIncomeRatio = incomeRatio.doubleValue();
	                            			 money = NumberTools.proportion(incomeMoney, staffIncomeRatio);
	                            			 incomeRatio = 0D;
	                            		 }
	                            	}
	                            }
	                        }
	            		}
	            		
	            		if(flag) {
	            			//如果没有进行单独配置，则使用合伙人的默认分成比例
	            			AgentRelationBusinessConfig busiConfig = AgentRelationBusinessConfigService.self().getByKeys(agent.getUserId(), 
	            					partnerProfitUser.getUserId(), businessOrder.getBusinessType());
	            			if(busiConfig != null && busiConfig.getIncomeRatio() > 0) {
	            				if(incomeRatio >= busiConfig.getIncomeRatio()) {
                       			 staffIncomeRatio = busiConfig.getIncomeRatio();
                       			 money = NumberTools.proportion(incomeMoney, staffIncomeRatio);
                       			 incomeRatio = incomeRatio - staffIncomeRatio;
                       		 }else {
                       			 staffIncomeRatio = incomeRatio.doubleValue();
                       			 money = NumberTools.proportion(incomeMoney, staffIncomeRatio);
                       			 incomeRatio = 0D;
                       		 }
	            			}
	            		}
                    }
                    //记录分成金额
                    profitMoney = profitMoney + money;
            		
            		User user = UserService.self().getById(partnerProfitUser.getUserId());
            		
            		BusinessOrderUserProfit userProfit = new BusinessOrderUserProfit();
                    userProfit.setTradeNo(businessOrder.getTradeNo());
                    userProfit.setOrderDate(businessOrder.getCreateDate());
                    userProfit.setDeviceFunCode(businessOrder.getDeviceFunCode());
                    userProfit.setBusinessType(businessOrder.getBusinessType());
                    userProfit.setUserId(user.getId());
                    userProfit.setAgentId(agent.getUserId());       //代理ID
                    userProfit.setAccountGroupId(accountGroupId);
                    userProfit.setName(user.getName());
                    userProfit.setPhone(user.getPhone());
                    userProfit.setRoleType(partnerProfitUser.getRoleType());
                    userProfit.setIncomeRatio(staffIncomeRatio);
                    userProfit.setMoney(money);
                    userProfit.setPlaceId(businessOrder.getPlaceId());
                    userProfit.setPlaceName(businessOrder.getPlaceName());
                    userProfit.setProvince(businessOrder.getProvince());
                    userProfit.setCity(businessOrder.getCity());
                    userProfit.setCityArea(businessOrder.getCityArea());
                    userProfit.setAreaCode(businessOrder.getAreaCode());
                    userProfit.setNote(partnerProfitUser.getNote());
                    userProfit.setState(BusinessOrderUserProfitEnum.State.Finish.index());
                    userProfit.setCreateDate(new Date());
                    userProfitList.add(userProfit);
            	}

                if(incomeRatio > 0) {
                    placeUser.setIncomeRatio(incomeRatio);      //网点代理的分成比例
                  
                    Long money = NumberTools.proportion(incomeMoney, incomeRatio);
                    profitMoney = profitMoney + money;
                    placeUser.setMoney(money);
                }
                
                incomeMoney = incomeMoney - profitMoney;
                
                if(incomeMoney > 0){
                	BusinessOrderUserProfit platformFlowUser = new BusinessOrderUserProfit();
                	platformFlowUser.setTradeNo(businessOrder.getTradeNo());
                	platformFlowUser.setOrderDate(businessOrder.getCreateDate());
                	platformFlowUser.setDeviceFunCode(businessOrder.getDeviceFunCode());
                	platformFlowUser.setBusinessType(businessOrder.getBusinessType());
                	platformFlowUser.setUserId(UserProfitConstants.PlatformFlowIncomeUserId);
                	platformFlowUser.setAccountGroupId(accountGroupId);
                	platformFlowUser.setName(UserProfitConstants.PlatformFlowIncomeUserName);
                	platformFlowUser.setRoleType(ERoleType.Sys.index());
                	platformFlowUser.setIncomeRatio(0D);		//默认
                	platformFlowUser.setMoney(incomeMoney);
                	platformFlowUser.setAgentId(agent.getUserId());       //代理ID
                	platformFlowUser.setPlaceId(businessOrder.getPlaceId());
                	platformFlowUser.setPlaceName(businessOrder.getPlaceName());
                	platformFlowUser.setProvince(businessOrder.getProvince());
                	platformFlowUser.setCity(businessOrder.getCity());
                	platformFlowUser.setCityArea(businessOrder.getCityArea());
                	platformFlowUser.setAreaCode(businessOrder.getAreaCode());
                	platformFlowUser.setState(BusinessOrderUserProfitEnum.State.Finish.index());
                	platformFlowUser.setCreateDate(new Date());
                    userProfitList.add(platformFlowUser);
                }else if(incomeMoney < 0){
                    throw new LogicException("分成超界，预计分成金额："+ NumberTools.getMoneyLiStr(incomeMoney) + "，实际分成金额：" + NumberTools.getMoneyLiStr(profitMoney));
                }

                //检查用户钱包是否存在，没有则添加默认
                for(BusinessOrderUserProfit userProfit : userProfitList) {
                    if (!ERoleType.Sys.index().equals(userProfit.getRoleType())) {    //排除系统
                        UserWallet userWallet = UserWalletService.self().getByKeys(userProfit.getUserId(), userProfit.getAccountGroupId());
                        if (userWallet == null) {
                            userWallet = new UserWallet();
                            userWallet.setUserId(userProfit.getUserId());
                            userWallet.setAccountGroupId(userProfit.getAccountGroupId());
                            if (!UserWalletService.self().add(userWallet)) {        //多线程创建时，保证最大可能成功分成
                                userWallet = UserWalletService.self().getByKeys(userProfit.getUserId(), userProfit.getAccountGroupId());
                                if (userWallet == null) {
                                    throw new LogicException("创建用户" + userProfit.getUserId() + "钱包失败");
                                }
                            }
                        }

                        if (!ERoleType.Agent.index().equals(userProfit.getRoleType()) && userProfit.getAgentId() != null) {
                            AgentRelationWallet wallet = AgentRelationWalletService.self().getByKeys(userProfit.getUserId(), userProfit.getAgentId(), userProfit.getAccountGroupId());
                            if (wallet == null) {
                                wallet = new AgentRelationWallet();
                                wallet.setUserId(userProfit.getUserId());
                                wallet.setRelationUserId(userProfit.getAgentId());
                                wallet.setAccountGroupId(userProfit.getAccountGroupId());
                                if (!AgentRelationWalletService.self().add(wallet)) {        //多线程创建时，保证最大可能成功分成
                                    wallet = AgentRelationWalletService.self().getByKeys(userProfit.getAgentId(),userProfit.getUserId(), userProfit.getAccountGroupId());
                                    if (wallet == null) {
                                        throw new LogicException("创建用户" + userProfit.getUserId() + "关联" + userProfit.getAgentId() + "钱包失败");
                                    }
                                }
                            }
                        }
                    }
                }

                if (add(businessOrder.getTradeNo(),userProfitList, operateInfo)) {
                    isSuccess = true;
                }
            }catch (LogicException e){
                divideError = e.getMessage();
            }finally {
                if(isSuccess){
                    BusinessOrderService.self(businessOrder.getCreateDate()).incomeDivideFinish(businessOrder.getTradeNo());
                    //记录操作日志
                    BusinessOrderLogService.self(businessOrder.getCreateDate()).add(businessOrder, operateInfo, ELogState.Success.index(), null);
                }else {
                    BusinessOrderService.self(businessOrder.getCreateDate()).incomeDivideFail(businessOrder.getTradeNo(),divideError);
                    //记录操作日志
                    BusinessOrderLogService.self(businessOrder.getCreateDate()).add(businessOrder, operateInfo, ELogState.Fail.index(), divideError);
                }
            }
            
            //代理介绍人分成
            if(isSuccess) {
            	try {
	            	AgentReferrerBusinessConfig referrerBusiCfg = AgentReferrerBusinessConfigService.self().getJoinByKeys(agent.getUserId(), platformUser.getBusinessType());
	            	if(referrerBusiCfg != null) {
		            	if(platformUser.getIncomeRatio() > config.getServiceChargeRatio()) {
		            		//计算分成比例
							Double referrerIncomeRatio = platformUser.getIncomeRatio() - config.getServiceChargeRatio();
							Double tempIncomeRatio = NumberTools.divide(referrerIncomeRatio, platformUser.getIncomeRatio(),2);
							//分成金额
							Double money = NumberTools.multiply(NumberTools.changeMoneyLi(platformUser.getMoney()),tempIncomeRatio);
							
							AgentReferrerOrderProfit referrerOrderProfit = new AgentReferrerOrderProfit();
							referrerOrderProfit.setTradeNo(platformUser.getTradeNo());
							referrerOrderProfit.setOrderDate(platformUser.getOrderDate());
							referrerOrderProfit.setUserId(referrerBusiCfg.getUserId());
							referrerOrderProfit.setReferrerUserId(referrerBusiCfg.getReferrerUserId());
							referrerOrderProfit.setReferrerUserName(referrerBusiCfg.getReferrerUser().getName());
							referrerOrderProfit.setReferrerUserPhone(referrerBusiCfg.getReferrerUser().getPhone());
							referrerOrderProfit.setBusinessType(platformUser.getBusinessType());
							referrerOrderProfit.setAccountGroupId(platformUser.getAccountGroupId());
							referrerOrderProfit.setOrderProfitMoney(platformUser.getMoney());
							referrerOrderProfit.setIncomeRatio(referrerIncomeRatio);
							referrerOrderProfit.setMoney(NumberTools.changeMoneyLi(money));
							referrerOrderProfit.setCreateDate(new Date());
							
							AgentReferrerOrderProfitService.self(businessOrder.getCreateDate()).saveToPay(referrerOrderProfit, operateInfo);
		            	}
	            	}
            	}catch(Exception e) {
            		log.error(e.getMessage(), e);
            	}
            }
            
            return isSuccess;
        }else{
            log.error("{{0}}订单分成锁失败",businessOrder.getTradeNo());
        }
        return false;
    }

    /**
     * 回滚分成
     * @param businessOrder
     * @param operateInfo
     * @return
     * @throws LogicException
     */
    public boolean revokeIncome(BusinessOrder businessOrder,OperateInfo operateInfo) throws LogicException {
        List<BusinessOrderUserProfit> userProfitList = this.findDivideByTradeNo(businessOrder.getTradeNo());
        if (userProfitList == null || userProfitList.size() == 0) {
            throw new LogicException("订单未分成");
        }
        
        if (BusinessOrderService.self(businessOrder.getCreateDate()).incomeCancelLock(businessOrder.getTradeNo())) {
            boolean isSuccess = false;
            String errorMsg = null;
            
            if(StringTools.isBlank(operateInfo.getOperateNote())) {
            	operateInfo.setOperateNote("撤销订单分成");
            }
            
            try {
                JdbcSession.begin();
                try {
                    boolean flag = true;
                    for (BusinessOrderUserProfit userProfit : userProfitList) {
                    	if(userProfit.getMoney() > 0) {
                    		//只处理分成金额大于0元的
	                        if (UserProfitConstants.PlatformServerUserId.equals(userProfit.getUserId())) {
	                            String note = userProfit.getTradeNo() + "订单收益分成";
	                            if (!ProjectWalletService.self().reduceMoney(ProjectWalletEnum.Type.ServerWallet.index(),userProfit.getAccountGroupId(),
	                                    userProfit.getMoney(), note)) {
	                                flag = false;
	                                errorMsg = "减少项目钱包金额失败";
	                            }
	                        }else if (UserProfitConstants.PlatformFlowIncomeUserId.equals(userProfit.getUserId())) {
	                            String note = userProfit.getTradeNo() + "订单收益分成";
	                            if (!ProjectWalletService.self().reduceMoney(ProjectWalletEnum.Type.FlowIncomeWallet.index(),userProfit.getAccountGroupId(),
	                                    userProfit.getMoney(), note)) {
	                                flag = false;
	                                errorMsg = "减少项目钱包金额失败";
	                            }
	                        }else if(ERoleType.Agent.index().equals(userProfit.getRoleType())){
	                            if (!UserWalletService.self().reduceMoney(userProfit.getUserId(),userProfit.getAccountGroupId(),userProfit.getMoney(), operateInfo)) {
	                                flag = false;
	                                errorMsg = "减少代理钱包金额失败";
	                            }
	                        }else if(userProfit.getAgentId() != null){
	                            if(!AgentRelationWalletService.self().reduceMoney(userProfit.getUserId(),userProfit.getAgentId()
	                                    ,userProfit.getAccountGroupId(),userProfit.getMoney(),operateInfo)){
	                                flag = false;
	                                errorMsg = "减少代理合伙人钱包金额失败";
	                            }
	                        }else{
	                            log.error("异常的用户分成信息：{{0:json}}",userProfit);
	                        }
                    	}
                        if(flag){
                            Conditions conditions = new Conditions(BusinessOrderUserProfit.class);
                            conditions.and().is("tradeNo",userProfit.getTradeNo());
                            conditions.and().is("userId",userProfit.getUserId());

                            BusinessOrderUserProfit updateEntity = new BusinessOrderUserProfit();
                            updateEntity.setState(BusinessOrderUserProfitEnum.State.Cancel.index());

                            flag = dao.updateNotNull(updateEntity,conditions) > 0;
                        }

                        if (!flag) {
                            break;
                        }
                    }
                    if (flag) {
                        JdbcSession.commit();
                        isSuccess = true;
                    }
                } catch (SQLException e) {
                    log.error(e.getMessage(), e);
                    errorMsg = "修改数据库失败，错误：" + e.getMessage();
                } catch (LogicException e) {
                    log.error(e.getMessage(), e);
                    errorMsg = e.getMessage();
                } finally {
                    JdbcSession.end();
                }
            } finally {
                if (isSuccess) {
                    BusinessOrderService.self(businessOrder.getCreateDate()).incomeCancelFinish(businessOrder.getTradeNo());
                    //记录操作日志
                    BusinessOrderLogService.self(businessOrder.getCreateDate()).add(businessOrder, operateInfo, ELogState.Success.index(), errorMsg);
                } else {
                    BusinessOrderService.self(businessOrder.getCreateDate()).incomeCancelFail(businessOrder.getTradeNo());
                    if(StringTools.isBlank(errorMsg)) {
                    	errorMsg = "系统错误";
                    }
                    //记录操作日志
                    BusinessOrderLogService.self(businessOrder.getCreateDate()).add(businessOrder, operateInfo, ELogState.Fail.index(), errorMsg);
                }
            }
            
            if(isSuccess) {
            	try {
	            	AgentReferrerOrderProfit referrerOrderProfit = AgentReferrerOrderProfitService
	            			.self(businessOrder.getCreateDate()).getByTradeNo(businessOrder.getTradeNo());
	            	if(referrerOrderProfit != null) {
	            		AgentReferrerOrderProfitService.self(businessOrder.getCreateDate()).revokeIncome(referrerOrderProfit, operateInfo);
	            	}
            	}catch(Exception e) {
            		log.error(e.getMessage(), e);
            	}
            }
  
            return isSuccess;
        }
        return false;
    }

    private boolean add(String tradeNo,List<BusinessOrderUserProfit> userProfitList, OperateInfo operateInfo) throws LogicException {
        if(userProfitList != null && userProfitList.size() > 0) {
            //获取旧的分成信息，删除不在分成的用户，修改又分成的用户，新增新分成的用户，作用是统计时减少撤销分成
            List<BusinessOrderUserProfit> oldUserProfitList = this.findByTradeNo(tradeNo);
            JdbcSession.begin();
            try{
                boolean flag = true;
                for(BusinessOrderUserProfit userProfit : userProfitList){
                    log.info("{{0}}订单分成，角色：{{1}}，用户ID：{{2}}，金额：{{3}}，比例：{{4}}",userProfit.getTradeNo()
                            ,userProfit.getRoleTypeName(),userProfit.getUserId(),userProfit.getMoneyStr(),userProfit.getIncomeRatio());
                    String note = userProfit.getTradeNo() + "订单收益分成";
                    operateInfo.setOperateNote(note);
                    
                    if(userProfit.getMoney() > 0) {		//只处理有金额的
	                    if(UserProfitConstants.PlatformServerUserId.equals(userProfit.getUserId())){
	                        if(!ProjectWalletService.self().addMoney(ProjectWalletEnum.Type.ServerWallet.index(),userProfit.getAccountGroupId(),userProfit.getMoney(),note)){
	                            flag = false;
	                        }
	                    }else if(UserProfitConstants.PlatformFlowIncomeUserId.equals(userProfit.getUserId())){
	                        if(!ProjectWalletService.self().addMoney(ProjectWalletEnum.Type.FlowIncomeWallet.index(),userProfit.getAccountGroupId(),userProfit.getMoney(),note)){
	                            flag = false;
	                        }
	                    }else if(ERoleType.Agent.index().equals(userProfit.getRoleType())){
	                        if(!UserWalletService.self().addMoney(userProfit.getUserId(),userProfit.getAccountGroupId(),userProfit.getMoney(),operateInfo)){
	                            flag = false;
	                        }
	                    }else if(userProfit.getAgentId() != null){
	                        if(!AgentRelationWalletService.self().addMoney(userProfit.getAgentId(),userProfit.getUserId()
	                                ,userProfit.getAccountGroupId(),userProfit.getMoney(),operateInfo)){
	                            flag = false;
	                        }
	                    }else{
	                        log.error("异常的用户分成信息：{{0:json}}",userProfit);
	                    }
                    }

                    if(flag){
                        boolean isAdd = true;
                        if(oldUserProfitList != null && oldUserProfitList.size() > 0){
                            for(BusinessOrderUserProfit oldUserProfit : oldUserProfitList){
                                if(oldUserProfit.getUserId().equals(userProfit.getUserId())){
                                    isAdd = false;
                                }
                            }
                        }

                        if(isAdd){
                            if(dao.insert(userProfit) <= 0){
                                flag = false;
                            }
                        }else {
                            Conditions conditions = new Conditions(BusinessOrderUserProfit.class);
                            conditions.and().is("tradeNo",userProfit.getTradeNo());
                            conditions.and().is("userId",userProfit.getUserId());

                            if(dao.updateNotNull(userProfit,conditions) <=0){
                                flag = false;
                            }
                        }
                    }

                    if(!flag){
                    	log.error("{{0}}用户分成失败，分成信息：{{1:json}}", userProfit.getUserId(),userProfit);
                    	break;
                    }
                }
                if(flag) {
                    if(oldUserProfitList != null && oldUserProfitList.size() > 0) {
                        for(BusinessOrderUserProfit oldUserProfit : oldUserProfitList){
                            boolean isDel = true;
                            for(BusinessOrderUserProfit userProfit : userProfitList) {
                                if (oldUserProfit.getUserId().equals(userProfit.getUserId())) {
                                    isDel = false;
                                    break;
                                }
                            }

                            if(isDel){
                                Conditions conditions = new Conditions(BusinessOrderUserProfit.class);
                                conditions.and().is("tradeNo",oldUserProfit.getTradeNo());
                                conditions.and().is("userId",oldUserProfit.getUserId());

                                if(dao.deleteByCondition(conditions) <=0){
                                    log.error("删除{{0}}订单多余分成用户{{1}}失败",oldUserProfit.getTradeNo(),oldUserProfit.getUserId());
                                    flag = false;
                                }
                            }
                        }
                    }

                    if(flag) {
                        JdbcSession.commit();
                        return true;
                    }
                }
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            } catch (LogicException e) {
                log.error(e.getMessage(), e);
            } finally {
                JdbcSession.end();
            }
        }
        return false;
    }
}
